#!/usr/bin/env python
from PyQt5.QtCore import pyqtSlot,pyqtProperty, pyqtSignal, QPointF, QUrl
from PyQt5.QtGui import QColor, QGuiApplication
from PyQt5.QtQml import qmlRegisterType
from PyQt5.QtQuick import (QQuickItem, QQuickView, QSGFlatColorMaterial,
        QSGGeometry, QSGGeometryNode, QSGNode)
from PyQt5.QtWidgets import QApplication,QFileDialog
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import QSettings
from PyQt5.QtQml import QQmlApplicationEngine
import sys
import platform
import os
import config_json
from pathlib import Path
import traceback
import logging
import bpptablecolumn
import bpptablecolumnlist
import bpptableheading
import bpptablemodel
from logging.handlers import RotatingFileHandler
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf8', buffering=1)
sys.stderr = open(sys.stderr.fileno(), mode='w', encoding='utf8', buffering=1)
handlers=[RotatingFileHandler(filename="report.log", maxBytes=10*1024*1024, encoding='utf-8',backupCount=3),logging.StreamHandler(sys.stdout)]
logging.basicConfig(level=logging.DEBUG,
                    format = '%(asctime)s - %(name)s - %(levelname)s -%(funcName)s - %(message)s',
                    handlers=handlers)
logging.info('begin')
class BezierCurve(QQuickItem):
    p1Changed = pyqtSignal(QPointF)
    @pyqtSlot()
    def import_click(self):
        FileDialog = QFileDialog(None)
        if config_json.setting["database"]!=None:
            folder = os.path.split(config_json.setting["database"])[0]
            if os.path.exists(folder):
                pass
            else:
                folder=os.path.join(os.path.expanduser('~'), "Desktop")
        else:
            folder=os.path.join(os.path.expanduser('~'), "Desktop")
        if config_json.setting["sblx"] in ["930"]:
            fil = "csv Files (*.csv);;All Files (*)"
        elif config_json.setting["sblx"] == "spec":
            fil = "xlsx Files (*.xlsx);;All Files (*)"
        elif config_json.setting["sblx"] in  ["6300","zwk"]:
            fil = "xls Files (*.xls);;All Files (*)"            
        elif config_json.setting["sblx"] == "ajl_pdf":
            fil = "pdf Files (*.pdf);;All Files (*)"
        elif config_json.setting["sblx"] == "icap":
            fil = "Html Files (*.html);;All Files (*)"
        elif config_json.setting["sblx"] in ["ajl8900"]:
            fil = "xlsx Files (*.xlsx);;All Files (*)"    
        elif config_json.setting["sblx"] in ["icap_q"]:
            fil = "xml Files (*.xml);;All Files (*)"                
        else:
            fil = "All Files (*)"
        FileDirectory = FileDialog.getOpenFileName(
            None, 'select import file', folder, fil)  # 选择目录，返回选中的路径
        # logging.info(FileDirectory)
        fname = FileDirectory[0]
        if fname == "":
            pass
        else:
            try:
                config_json.setting["database"] = fname
                self.import_file(fname)
            except:
                traceback.print_exc()    
    def import_file(self, fname):
        self.export_num=0
        logging.info(fname)
        if config_json.setting["sblx"] in ["icap","icap_q"]:
            pass
            # self.ui.lineEdit_filename.setText(os.path.split(os.path.split(fname)[0])[1])
        else:
            # self.ui.lineEdit_filename.setText(os.path.splitext(os.path.basename(fname))[0])
            pass
        self.clearResult()
        self.query()
    def clearResult(self):
        pass
    def query(self):
        global db
        print(db)
        if db==None or  not db.inited:
            return
        n=self.ui.spinBox_day.value()
        self.objects=db.getDataDays(n)
        # if self.objects and len(self.objects)>0:
        #     logging.info(dir(self.objects[0]))
        self.objects2=[]
        self.init_grid()
        self.firstChannel()
        pass
    def firstChannel(self):
        try:
            groups = {}
            for i in range(len(self.db.properties)):
                f = self.db.properties[i]
                if f.get("ele") is None:
                    pass
                else:
                    element = f["ele"][0]
                    if groups.get(element) is None:
                        groups[element] = []
                    groups[element].append(f)
            for one in groups.keys():
                # logging.info(groups[one])
                for i in range(len(groups[one])):  # wave in groups[one]:
                    if i == 0:
                        groups[one][i]["visible"] = True
                    else:
                        groups[one][i]["visible"] = False
            for i in range(len(self.db.properties)):
                if self.db.properties[i].get("ele") is None:
                    pass
                else:
                    self.columnVisible(i, self.db.properties[i]["visible"])

        except ValueError as e:
            pass        
    def init_grid(self):
        try:
            self.objects.sort(reverse=False, key=lambda a:a.num)
            self.objects2.sort(reverse=False, key=lambda a:a.num)
        except TypeError:
            pass 

        self.resetItems()
        self.model.setObjects(self.objects,self.db.properties)
        self.ui.tableView.setModel(self.model)
        
        self.model2.setObjects(self.objects2,self.db.properties)
        self.ui.tableView_report.setModel(self.model2)
        for i, prop in enumerate(self.db.properties):
            logging.info([i,prop])
            if prop.get('delegate')=="edit":
                self.ui.tableView.setItemDelegateForColumn(i, self.editDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.editDelegate)
            elif prop.get('delegate')=="floatEdit":
                self.ui.tableView.setItemDelegateForColumn(i, self.floatEdit)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.floatEdit)
            elif prop.get('delegate')=="double":
                self.ui.tableView.setItemDelegateForColumn(i, self.dblViewDele)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.dblViewDele)
            elif prop.get('delegate')=="comboEdit":
                self.ui.tableView.setItemDelegateForColumn(i, self.comboDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.comboDelegate)
            elif prop.get('delegate')=="date":
                self.ui.tableView.setItemDelegateForColumn(i, self.dateDelegate)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.dateDelegate)
            elif prop.get('delegate')==None:
                self.ui.tableView.setItemDelegateForColumn(i, self.notedit)
                self.ui.tableView_report.setItemDelegateForColumn(i, self.notedit)        
    @pyqtSlot(str,result=str)
    def gettime(self,format):
        curr_time = time.strftime("%H:%M:%S", time.localtime())
        return curr_time
    @pyqtSlot(str)
    def set_text_msg(self, msg):
        # 获取qml中的Text对象
        child = self.obj.findChild(QQuickItem, "text1")
        # 获取对象属性
        p = child.property("text")
        # 设置对象属性
        child.setProperty("text", p + msg)
    @pyqtProperty(QPointF, notify=p1Changed)
    def p1(self):
        return self._p1

    @p1.setter
    def p1(self, p):
        if self._p1 != p:
            self._p1 = QPointF(p)
            self.p1Changed.emit(p)
            self.update()

    p2Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p2Changed)
    def p2(self):
        return self._p2

    @p2.setter
    def p2(self, p):
        if self._p2 != p:
            self._p2 = QPointF(p)
            self.p2Changed.emit(p)
            self.update()

    p3Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p3Changed)
    def p3(self):
        return self._p3

    @p3.setter
    def p3(self, p):
        if self._p3 != p:
            self._p3 = QPointF(p)
            self.p3Changed.emit(p)
            self.update()

    p4Changed = pyqtSignal(QPointF)

    @pyqtProperty(QPointF, notify=p4Changed)
    def p4(self):
        return self._p4

    @p4.setter
    def p4(self, p):
        if self._p4 != p:
            self._p4 = QPointF(p)
            self.p4Changed.emit(p)
            self.update()

    segmentCountChanged = pyqtSignal(int)

    @pyqtProperty(int, notify=segmentCountChanged)
    def segmentCount(self):
        return self._segmentCount

    @segmentCount.setter
    def segmentCount(self, count):
        if self._segmentCount != count:
            self._segmentCount = count
            self.segmentCountChanged.emit(count)
            self.update()

    def __init__(self, parent=None):
        super(BezierCurve, self).__init__(parent)

        self._p1 = QPointF(0, 0)
        self._p2 = QPointF(1, 0)
        self._p3 = QPointF(0, 1)
        self._p4 = QPointF(1, 1)

        self._segmentCount = 32

        self._root_node = None

        self.setFlag(QQuickItem.ItemHasContents, True)

    def updatePaintNode(self, oldNode, nodeData):
        if self._root_node is None:
            self._root_node = QSGGeometryNode()

            geometry = QSGGeometry(QSGGeometry.defaultAttributes_Point2D(),
                    self._segmentCount)
            geometry.setLineWidth(2)
            geometry.setDrawingMode(QSGGeometry.GL_LINE_STRIP)
            self._root_node.setGeometry(geometry)
            self._root_node.setFlag(QSGNode.OwnsGeometry)

            material = QSGFlatColorMaterial()
            material.setColor(QColor(255, 0, 0))
            self._root_node.setMaterial(material)
            self._root_node.setFlag(QSGNode.OwnsMaterial)
        else:
            geometry = self._root_node.geometry()
            geometry.allocate(self._segmentCount)

        w = self.width()
        h = self.height()
        vertices = geometry.vertexDataAsPoint2D()

        for i in range(self._segmentCount):
            t = i / float(self._segmentCount - 1)
            invt = 1 - t

            pos = invt * invt * invt * self._p1 \
                    + 3 * invt * invt * t * self._p2 \
                    + 3 * invt * t * t * self._p3 \
                    + t * t * t * self._p4

            vertices[i].set(pos.x() * w, pos.y() * h)

        self._root_node.markDirty(QSGNode.DirtyGeometry)

        return self._root_node

def main0():
    if platform.uname().system=="Windows":
        pass
    else:
        from Watcher import Watcher
        Watcher()
    QApplication.setApplicationName("装箱单")
    QApplication.setOrganizationName("QtProject")

    app = QApplication(sys.argv)
    # print(dir(app))
    QIcon.setThemeName("gallery")

    settings = QSettings()
    # if not os.environ.get("QT_QUICK_CONTROLS_STYLE"):
    #     style_name = settings.value("style")
    #     if style_name:
    #         QQuickStyle.setStyle(style_name)
    # QQuickStyle.setStyle("Material")
    engine = QQmlApplicationEngine()
    # built_in_styles = ["Basic", "Fusion", "Imagine", "Material", "Universal"]
    # if platform.system() == "Darwin":
    #     built_in_styles.append("macOS")
    # elif platform.system() == "Windows":
    #     built_in_styles.append("Windows")
    # engine.setInitialProperties({"builtInStyles": built_in_styles})

    # Get the path of the current directory, and then add the name
    # of the QML file, to load it.
    qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")
    qmlRegisterType(bpptablemodel.BTModel, "BppTable", 1, 0, "BTModel")
    qml_file = Path(__file__).parent / 'main.qml'
    # qml_file = Path(__file__).parent / 'C1.qml'
    engine.load(str(qml_file))

    if not engine.rootObjects():
        sys.exit(-1)

    sys.exit(app.exec())
def main1():
    app = QGuiApplication(sys.argv)

    qmlRegisterType(BezierCurve, "CustomGeometry", 1, 0, "BezierCurve")

    view = QQuickView()
    format = view.format()
    format.setSamples(16)
    view.setFormat(format)

    view.setSource(QUrl('mainw.qml'))
    view.show()

    sys.exit(app.exec_())
if __name__ == '__main__':
    config_json.read_setting()
    main0()
